package com.iot08.admin.service;

import com.iot08.admin.service.page.PageVO;
import com.iot08.admin.service.page.PageableImpl;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.VideoModel;
import com.iot08.common.utils.UUIDGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Description: 视频规则业务处理
 * @time: 2020/8/24 10:34
 * @author: Rock
 */
@Service
public class VideoModelService {

    @Resource(name = "appMongoTemplate")
    private MongoTemplate mongoTemplate;
    @Resource
    private DeviceService deviceService;
    @Resource
    private OperationService operationService;

    /**
     * @param [page]
     * @Description: 视频规则列表
     * @time: 2020/8/25 11:18
     * @author: Rock
     * @version 1.0
     */
    public Page<VideoModel> list(PageVO page) {
        PageableImpl pageable = new PageableImpl();
        page.setSort(Sort.by(Sort.Order.desc("createtime")));
        pageable.setPage(page);

        Criteria criteria = new Criteria();
        if (StringUtils.isNotEmpty(page.getSearchValue())) {
            criteria.and("name").regex(".*?" + page.getSearchValue() + ".*?", "i");
        }

        Query query = new Query().addCriteria(criteria);
        long count = mongoTemplate.count(query, VideoModel.class);
        page.setTotalResult((int) count);
        List<VideoModel> list = mongoTemplate.find(query.with(pageable), VideoModel.class);
        Page<VideoModel> result = new PageImpl<VideoModel>(list, pageable, count);
        return result;
    }

    /**
     * @param [video]
     * @Description: 保存
     * @time: 2020/8/25 16:37
     * @author: Rock
     * @version 1.0
     */
    public void save(VideoModel video, SysUser user, String ip) {
        if (video != null) {
            video.setId(UUIDGenerator.generate());
            video.setImportNum(0);
            video.setCreatetime(new Date());
            mongoTemplate.save(video);
            operationService.add(user, ip, "视频规则", "添加",
                    String.format("添加视频规则: %s ", video.getName()));
        }
    }

    /**
     * @param [id]
     * @Description:
     * @time: 2020/8/25 11:25
     * @author: Rock
     * @version 1.0
     */
    public VideoModel getById(String id) {
        return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), VideoModel.class);
    }

    /**
     * @param [name]
     * @time: 2020/8/25 17:42
     * @author: Rock
     * @version 1.0
     */
    public VideoModel getByName(String name) {
        return mongoTemplate.findOne(new Query(Criteria.where("name").is(name)), VideoModel.class);
    }

    /**
     * @Description: 获取全部列表
     * @time: 2020/8/24 10:39
     * @author: Rock
     * @version 1.0
     */
    public List<VideoModel> listAll() {
        return mongoTemplate.findAll(VideoModel.class);
    }

    /**
     * @param [id]
     * @Description: 更新绑定状态
     * @time: 2020/8/24 10:55
     * @author: Rock
     * @version 1.0
     */
    public void updateBinding(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("isBinding", 1);
        update.set("modifytime", new Date());
        mongoTemplate.updateFirst(query, update, VideoModel.class);
    }

    /**
     * @param [video]
     * @Description: 更新
     * @time: 2020/8/25 16:38
     * @author: Rock
     * @version 1.0
     */
    public String update(VideoModel video, SysUser user, String ip) {
        if (video != null) {
            VideoModel vm = getByName(video.getName());
            if (vm != null && !vm.getName().equals(video.getName())) {
                return "该视频规则名称已存在";
            }
            Query query = new Query(Criteria.where("_id").is(video.getId()));
            Update update = new Update();
            update.set("name", video.getName());
            update.set("display_resolution", video.getDisplayResolution());
            update.set("watch_display_resolution", video.getWatchDisplayResolution());
            update.set("one_call_time", video.getOneCallTime());
            update.set("call_interval", video.getCallInterval());
            update.set("all_call_time", video.getAllCallTime());
            update.set("des_note", video.getDesNote());
            update.set("modifytime", new Date());
            mongoTemplate.updateFirst(query, update, VideoModel.class);
            operationService.add(user, ip, "视频规则", "编辑",
                    String.format("编辑视频规则: %s ", video.getName()));
        }
        return "success";
    }

    /**
     * @param [id]
     * @Description: 删除
     * @time: 2020/8/25 16:29
     * @author: Rock
     * @version 1.0
     */
    public String del(String id, SysUser user, String ip) {
        Query query = new Query(Criteria.where("_id").is(id));
        VideoModel vm = mongoTemplate.findOne(query, VideoModel.class);
        if (vm.getImportNum() != null && vm.getImportNum() > 0) {
            return "存在设备号引用该视频规则，无法删除";
        } else {
            VideoModel video = getById(id);
            operationService.add(user, ip, "视频规则", "删除",
                    String.format("删除视频规则: %s ", video.getName()));
            mongoTemplate.remove(query, VideoModel.class);
        }
        return "";
    }

    /**
     * 根据id更新设备导入数量
     * @param [id]
     * @time: 2020/8/28 11:13
     * @author: Rock
     * @version 1.0
     */
    /*public void updateImportNum(String id){
        Query query = new Query(Criteria.where("_id").is(id));
        VideoModel models = mongoTemplate.findOne(query, VideoModel.class);
        if(models != null){
            Update update = new Update();
            update.set("import_num", deviceService.countImportNumByVideoModelId(id));
            mongoTemplate.updateFirst(query, update, VideoModel.class);
        }
    }*/

    /**
     * @time: 2020/11/12 14:52
     * @author: Rock
     * @version 1.0
     */
    public void updateImportNumJob() {
        List<String> ids = mongoTemplate.findDistinct("_id", VideoModel.class, String.class);
        for (String id : ids) {
            if (StringUtils.isEmpty(id)) {
                continue;
            }
            Query query = new Query(Criteria.where("_id").is(id));
            Update update = new Update();
            update.set("import_num", deviceService.countImportNumByVideoModelId(id));
            mongoTemplate.updateFirst(query, update, VideoModel.class);
        }
    }

}
